package com.leyou.user.service.service;

import com.leyou.common.utils.NumberUtils;
import com.leyou.user.entity.TbUser;
import com.leyou.user.service.mapper.UserMapper;
import com.leyou.user.utils.CodecUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;
    
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String key_prefix = "user:code:phone:";
    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    public Boolean checkUserData(String data, Integer type) {
        TbUser tbUser = new TbUser();
        if(type == 1){
            tbUser.setUsername(data);
        }else if(type==2){
            tbUser.setPhone(data);
        }else {
            return  null;
        }
        List<TbUser> select = userMapper.select(tbUser);
        int i = userMapper.selectCount(tbUser);
        return userMapper.selectCount(tbUser)==0;
    }


    public Boolean sendVerifyCode(String phone) {
        TbUser tbUser = new TbUser();
        tbUser.setPhone(phone);
        //校验手机号是否已经被注册过
        if(userMapper.selectCount(tbUser)!=0){
            return null;//手机号已经存在
        }
        //生成随6位验证码
        String code = NumberUtils.generateCode(6);
        try {
            Map<String,String> map =  new HashMap<>();
            map.put("phone", phone);
            map.put("code", code);
            //发送消息到rabbitMQ
            amqpTemplate.convertAndSend("sms.verify.code",map );
            //存到redis中
            redisTemplate.boundValueOps(key_prefix+phone).set(code,5, TimeUnit.MINUTES);
            return true;//成功发送
        } catch (AmqpException e) {
            e.printStackTrace();
            LOGGER.error("发送短信失败。phone：{}， code：{}", phone, code);
            return  false;
        }

    }

    /**
     * 注册用户信息
     * @param user
     * @param code
     * @return
     */
    public Boolean register( TbUser user, String code) {
        String key = key_prefix+user.getPhone();
        //从redis中获取验证码
        String codeCache = this.redisTemplate.opsForValue().get(key);
        //判断验证码是否正确
        if(!StringUtils.equals(code, codeCache)){
            return false;//验证码错误   返回
        }
        user.setId(null);
        //获取盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        //对密码进行加密
        user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));
        //创建时间
        user.setCreated(new Date());

        Boolean bool = userMapper.insertSelective(user)==1;
        if(bool){
            //如果注册成功就删除redis中的短信
            try {
                this.redisTemplate.delete(key);
            } catch (Exception e) {
                LOGGER.error("删除缓存验证码失败，code:{}",code,e);
            }
        }
        return bool;



    }

    /**
     *根据用户名和密码查询用户
     * @param username
     * @param password
     * @return
     */
    public TbUser queryUser(String username,String password) {
        TbUser tbUser = new TbUser();
        tbUser.setUsername(username);
        TbUser tbUser1 = userMapper.selectOne(tbUser);
        //校验用户名
        if(tbUser1==null){
            return null;//用户名不存在；
        }
        //校验密码
        if(StringUtils.equals(tbUser1.getPassword(), CodecUtils.md5Hex(password, tbUser1.getSalt()))){
            return tbUser1;//正确
        }
        return null;//失败

    }
}
